package org.edu.modules.scheduleCommon.dto;

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Test {
    // 使用ISO周规则（周一为周起始）
    private static final WeekFields CN_WEEK_FIELDS = WeekFields.of(DayOfWeek.MONDAY, 1);


    // 校历条目数据结构
    public static class CalendarEntry {
        private String month;
        private String date;
        private int year;
        private int weekNumber;
        private int dayOfWeek;

        public CalendarEntry(String month, String date, int year, int weekNumber, int dayOfWeek) {
            this.month = month;
            this.date = date;
            this.year = year;
            this.weekNumber = weekNumber;
            this.dayOfWeek = dayOfWeek;
        }

        // Getters
        public String getMonth() {
            return month;
        }

        public String getDate() {
            return date;
        }

        public int getYear() {
            return year;
        }

        public int getWeekNumber() {
            return weekNumber;
        }

        public int getDayOfWeek() {
            return dayOfWeek;
        }
    }

    /**
     * 生成校历
     *
     * @param startDate 学期开始日期
     * @param endDate   学期结束日期
     * @return 按月份分组的校历数据
     */
    public static Map<String, List<CalendarEntry>> generateCalendar(

            LocalDate startDate,
            LocalDate endDate) {

        Map<String, List<CalendarEntry>> calendar = new LinkedHashMap<>();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 计算总天数差
        long totalDays = ChronoUnit.DAYS.between(startDate, endDate) + 1;

        // 生成每一天的条目
        for (int i = 0; i < totalDays; i++) {
            LocalDate currentDate = startDate.plusDays(i);

            DayOfWeek startDayOfWeek = startDate.getDayOfWeek();
            int startDayValue = startDayOfWeek.getValue(); // 1-7

            // 计算到下一个周一的天数偏移量
            int offset = (startDayValue == 1) ? 0 : (7 - (startDayValue - 1)) % 7;

            int weekNumber;
            if (i < offset) {
                // 学期开始日期到下个周一前的天数，归属第1周
                weekNumber = 1;
            } else {
                // 对齐后，每7天为一周
                weekNumber = ((i - offset) / 7) + 2;
            }

            // 计算相对于学期开始的周数（从1开始）
            //int weekNumber = (i / 7) + 1;

            // 计算基于周一的周次
            //int weekNumber = currentDate.get(CN_WEEK_FIELDS.weekOfWeekBasedYear());


            // 格式化日期
            String formattedDate = currentDate.format(dateFormatter);
            String month = currentDate.getMonthValue() + "月";
            int year = currentDate.getYear();


            // 获取星期几（中文显示）
           // int dayOfWeek = convertToChineseDay(currentDate.getDayOfWeek());


            int dayOfWeek=currentDate.getDayOfWeek().getValue();

            // 创建条目
            CalendarEntry entry = new CalendarEntry(
                    month,
                    formattedDate,
                    year,
                    weekNumber,
                    dayOfWeek
            );

            // 按月份分组
            String monthKey = String.format("%d-%02d", year, currentDate.getMonthValue());
            calendar.computeIfAbsent(monthKey, k -> new ArrayList<>()).add(entry);
        }

        return calendar;
    }


    // 将DayOfWeek转换为中文星期
    private static int convertToChineseDay(DayOfWeek dayOfWeek) {
        //String[] days = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
        //return days[dayOfWeek.getValue() - 1];
        return dayOfWeek.getValue();
    }

    public static void main(String[] args) {

        // 1. UNIX 时间戳（秒）
        long startTimestamp = 1741858335;
        // 2. 转换为 Instant（时间戳起点为 1970-01-01T00:00:00Z）
        Instant instant = Instant.ofEpochSecond(startTimestamp);
        // 3. 转换为指定时区的 ZonedDateTime（例如 UTC）
        //LocalDate utcDate = instant.atZone(ZoneId.of("UTC")).toLocalDate();
        // 4. 或者使用系统默认时区
        LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();

        // 1. UNIX 时间戳（秒）
        long endTimestamp = 1737302400;
        // 2. 转换为 Instant（时间戳起点为 1970-01-01T00:00:00Z）
        Instant instant2 = Instant.ofEpochSecond(endTimestamp);
        // 3. 转换为指定时区的 ZonedDateTime（例如 UTC）
        //LocalDate utcDate = instant.atZone(ZoneId.of("UTC")).toLocalDate();
        // 4. 或者使用系统默认时区
        LocalDate localDate2 = instant2.atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate start =localDate;
        LocalDate end = localDate2;
        System.out.println("start：" + start);
        System.out.println("end：" + end);

        long nowTime = System.currentTimeMillis() / 1000;
        Integer nowTimeInt = new Long(nowTime).intValue();
        Instant instant3 = Instant.ofEpochSecond(nowTimeInt);
        LocalDate localDate3 = instant3.atZone(ZoneId.systemDefault()).toLocalDate();
        System.out.println("localDate3：" + localDate3);
        //LocalDate start = LocalDate.of(2024, 8, 30);
        //LocalDate end = LocalDate.of(2025, 1, 31);

        /*Map<String, List<CalendarEntry>> calendar = generateCalendar(start, end);

        // 打印示例输出
        calendar.forEach((month, entries) -> {
            System.out.println("\n月份：" + month);
            entries.forEach(entry ->
                    System.out.printf("%s | 周次：%02d | %s%n",
                            entry.getDate(),
                            entry.getWeekNumber(),
                            entry.getDayOfWeek()));
        });*/
    }
}
